<?php

class DB_ClientEnergySupplierBind extends DB_CRUD {
    protected $table = 'client_es_bind';
    protected $PK = 'id';
    protected $fields = array('client_id', 'es_id', 'start_date', 'end_date');

    public function save($data) {
        $tDate = new DateTime($data->changeDate);
        $currentRecord = $this->getCurrentRecord($data->client->id);
        if ($currentRecord && $currentRecord['id']) {
            $oldSaveData = array(
                'id' => $currentRecord['id'],
                'client_id' => $data->client->id,
            	//'es_id' => $data->oldES->id,
            	'end_date' => $tDate->format('Y-m-d H:i:s'),
            );
            parent::save((object)$oldSaveData);
        }

        $newSaveData = array(
            'client_id' => $data->client->id,
        	'es_id' => $data->newES->id,
        	'start_date' => $tDate->format('Y-m-d H:i:s'),
        );
        parent::save((object)$newSaveData);
    }

    public function getCurrentRecord($clientId) {
        $sql = "SELECT * FROM {$this->table} WHERE client_id = :client_id AND end_date = '0000-00-00' ORDER BY start_date DESC LIMIT 1";
        $sth = $this->db->prepare($sql);
        $sth->bindValue(":client_id", $clientId);
        //$sth->bindValue(":es_id", $esId);
        $sth->execute();
        return $sth->fetch(PDO::FETCH_ASSOC);
    }
}
